package com.liyu.iblog.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.liyu.iblog.dao.BlogDao;
import com.liyu.iblog.dao.CommentDao;
import com.liyu.iblog.domain.Blog;
import com.liyu.iblog.domain.Comment;
import com.liyu.iblog.utils.MD5Util;

@Service("commentService")
public class CommentServiceImpl implements CommentService {

    private CommentDao commentDao;
    private BlogDao blogDao;
    
    @Autowired
    public CommentServiceImpl(CommentDao commentDao, BlogDao blogDao) {
        this.commentDao = commentDao;
        this.blogDao = blogDao;
    }
    
    @Override
    public synchronized void createCommentForBlog(Object blogId, Comment comment) {       
        //generate the avatar hash
        comment.setPublisherEmail(comment.getPublisherEmail().trim().toLowerCase());
        comment.setAvatarLink(
                "http://www.gravatar.com/avatar/" + 
                MD5Util.md5Hex(comment.getPublisherEmail()) + ".jpg");
        //format the publisher website
        if (comment.getPublisherWebsite() != null && !comment.getPublisherWebsite().trim().isEmpty()) {
            String website = comment.getPublisherWebsite().trim().toLowerCase();
            if (website.isEmpty())
                comment.setPublisherWebsite(null);
            if (!website.startsWith("http://")) 
                comment.setPublisherWebsite("http://" + website);
        }
        Blog blog = blogDao.get(blogId);
        blog.setCommentCount(blog.getCommentCount() + 1); 
        blog.addComment(comment);
        blogDao.save(blog);
    }

    @Override
    public List<Comment> getCommentsByBlogId(Object id) {
        List<Comment> comments = commentDao.getCommentsByBlogKey(id);
        /*remove the useless inform, prevent them from muddling the JASON array.
          this can not be done in the Dao, cauz these comment are managed entity,
          the change will be reflected in the persistence storage*/
        for(Comment c : comments) {
            c.setKey(null);
            c.setBlog(null);
        }
        return comments;
    }

    @Override
    public void removeCommentByEncodedKey(String encodedKey) {
        Key key = KeyFactory.stringToKey(encodedKey);
        commentDao.delete(key);
    }
    
}
